<?php


namespace app\middleware;


use Illuminate\Database\Events\QueryExecuted;
use support\Db;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class SqlLogMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
        Db::connection()->listen(function (QueryExecuted $queryExecuted){
//            dump("[{$queryExecuted->time} ms] {$queryExecuted->sql}");


            $sql = str_replace('?', "'%s'", $queryExecuted->sql);
            $log = vsprintf($sql, $queryExecuted->bindings);
            dump("[".date('Y-m-d H:i:s')."] [{$queryExecuted->time} ms] {$log}");



            if (env('OPEN_SQL_LOG', false)) {
                $data = date('Y-m-d');
                $this->putLog('sql'. '-' . $data, $log, $queryExecuted->time);
            }

            if ($queryExecuted->time >= 5000) {
                $this->putLog('timeLimit-5s', $log, $queryExecuted->time);
            }

            if ($queryExecuted->time >= 1000) {
                $this->putLog('timeLimit-1s', $log, $queryExecuted->time);
            }


        });
        return $handler($request);
    }
    private function putLog($file = 'app', $content = '', $time='')
    {
        $cut_line = str_repeat("-", 100);
        $dir = $_ENV['LOG_ROOT'].'/sql';
//        is_dir($dir) or mkdir ($dir, 0777, true); // 文件夹不存在则创建
        $content = '[' . date('Y-m-d H:i:s') . '] [useTime:'.$time.'ms] uid:'.(defined('USER_ID')?USER_ID:'').' sql:' . $content;
        @file_put_contents($dir.'/'. $file . '.log', $content . "\n" . $cut_line . "\n\n", FILE_APPEND);
    }
}